package io.renren.utils;

import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * @author:yuchen
 * @createTime:2021/3/12 10:42
 */
@Slf4j
public class FileUtil {

    public static File getFileInByUrl(String fileUrl) {
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        BufferedOutputStream stream = null;
        InputStream inputStream = null;
        FileOutputStream fileOutputStream = null;
        File file = null;
        HttpURLConnection conn = null;
        try {
            String imgName = fileUrl.substring(fileUrl.lastIndexOf("/") + 1);
            URL imageUrl = new URL(fileUrl);
            conn = (HttpURLConnection) imageUrl.openConnection();
//			conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
            //设置请求头
            conn.setRequestProperty("Charsert", "UTF-8");
            conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");//设置参数类型是json格式
            conn.setRequestProperty("Connection", "Keep-Alive");
            inputStream = conn.getInputStream();
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = inputStream.read(buffer)) != -1) {
                outStream.write(buffer, 0, len);
            }
            file = new File(imgName);
            fileOutputStream = new FileOutputStream(file);
            stream = new BufferedOutputStream(fileOutputStream);
            stream.write(outStream.toByteArray());
        } catch (Exception e) {
            log.error("获取文件，Error", e);
        } finally {
            if (stream != null) {
                try {
                    stream.close();
                } catch (IOException ignored) {
                }
            }
            if (fileOutputStream != null) {
                try {
                    fileOutputStream.close();
                } catch (IOException ignored) {
                }
            }
            try {
                outStream.close();
            } catch (IOException ignored) {
            }

            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException ignored) {
                }
            }
            if (conn != null) {
                conn.disconnect();
            }
        }
        return file;
    }

    public static InputStream getInputByUrl(String fileUrl) {
        InputStream inputStream = null;
        HttpURLConnection conn = null;
        try {
            URL imageUrl = new URL(fileUrl);
            conn = (HttpURLConnection) imageUrl.openConnection();
            conn.setRequestProperty("Charsert", "UTF-8");
            conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");//设置参数类型是json格式
            conn.setRequestProperty("Connection", "Keep-Alive");
            inputStream = conn.getInputStream();
        } catch (Exception e) {
            log.error("获取文件，Error", e);
        } finally {
            if (conn != null) {
                conn.disconnect();
            }
        }
        return inputStream;
    }

    public static File getFileByUrl(String fileUrl) {
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        BufferedOutputStream stream = null;
        InputStream inputStream = null;
        FileOutputStream fileOutputStream = null;
        File file = null;
        HttpURLConnection conn = null;
        try {
            String imgName = fileUrl.substring(fileUrl.lastIndexOf("/") + 1);
            URL imageUrl = new URL(fileUrl);
            conn = (HttpURLConnection) imageUrl.openConnection();
//			conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
            //设置请求头
            conn.setRequestProperty("Charsert", "UTF-8");
            conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");//设置参数类型是json格式
            conn.setRequestProperty("Connection", "Keep-Alive");
            inputStream = conn.getInputStream();
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = inputStream.read(buffer)) != -1) {
                outStream.write(buffer, 0, len);
            }
            file = new File(imgName);
            fileOutputStream = new FileOutputStream(file);
            stream = new BufferedOutputStream(fileOutputStream);
            stream.write(outStream.toByteArray());
        } catch (Exception e) {
            log.error("获取文件，Error", e);
        } finally {
            if (stream != null) {
                try {
                    stream.close();
                } catch (IOException ignored) {
                }
            }
            if (fileOutputStream != null) {
                try {
                    fileOutputStream.close();
                } catch (IOException ignored) {
                }
            }
            try {
                outStream.close();
            } catch (IOException ignored) {
            }

            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException ignored) {
                }
            }
            if (conn != null) {
                conn.disconnect();
            }
        }
        return file;
    }

    public static String getFileType(String fileUrl) {
        String fileType = fileUrl.substring(fileUrl.lastIndexOf("."));
        // 如果从url获取的文件类型长度大于7个，说明不是正常文件类型
        if (fileType.length() > 7) {
            if (fileType.contains("jpg")) {
                fileType = ".jpg";
            } else if (fileType.contains("PNG")) {
                fileType = ".PNG";
            } else {
                fileType = ".PNG";
            }
        }
        return fileType;
    }


    public static void deleteAllFile(File rootFile) {
        if (rootFile != null) {
            if (rootFile.isFile()) {
                rootFile.delete();
            } else {
                File[] files = rootFile.listFiles();// 将非空文件夹转换成File数组
                for (File file : files) {//使用foreach语句遍历文件数组
                    deleteAllFile(file);// 删除指定文件夹下的所有非空文件夹（包括file）
                }
                rootFile.delete();// 删除指定文件夹下的所有空文件夹
            }
        }
    }

    public static String getFileNameByUrl(String fileUrl) {

        return fileUrl.substring(fileUrl.lastIndexOf("/") + 1);
    }

    public static void main(String[] args) {
        String fileNameByUrl = getFileNameByUrl("http:///20210131DE11UM_PayVoucher_2021-02-04.jpg");
        System.out.println(fileNameByUrl);
    }

}
